﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VCN.App.DataAccessLayer;
using VCN.App.DataTransferObjects;
using System.Data;

namespace VCN.admin.UC
{
    public partial class ViewUser : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                lblMessage.Visible = false;
                if (!IsPostBack)
                {
                    drdRole.Items.Add(new ListItem("Admin", "0"));
                    drdRole.Items.Add(new ListItem("User", "1"));
                    BindData();
                }
                if (Request.QueryString["lock"] != null)
                {
                    int v_i_UId = int.Parse(Request.QueryString["UId"].ToString());
                    if (Request.QueryString["lock"].Equals("true"))
                    {
                        if (this.LockUser(v_i_UId))
                        {
                            lblMessage.Visible = true;
                            lblMessage.Text = "Lock user thành công";
                            BindData();
                        }
                    }
                    else
                    {
                        if (this.UnLockUser(v_i_UId))
                        {
                            lblMessage.Visible = true;
                            lblMessage.Text = "UnLock user thành công";
                            BindData();
                        }
                    }
                }
                if (Request.QueryString["pass"] != null && Request.QueryString["pass"].ToString().Equals("ok"))
                {
                    string somescript;
                    somescript = "<script language='javascript'>alert('Đổi mật khẩu thành công')</script>";
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "succeed", somescript);
                }
           }
            catch (Exception v_e)
            {
                lblMessage.Text= v_e.Message;
            }
        }

        #region Members
        UsersDAO m_users_dao = new UsersDAO();
        Users m_user = new Users();
        #endregion

        #region Private Methods
        private void BindData()
        {
            grvGroupnews.DataSource = m_users_dao.getAllUsersAcc();
            grvGroupnews.DataBind();
        }
        //private DataTable GetTable()
        //{
        //    DataTable v_dt_table = new DataTable();
        //    DataTable v_dt_tableUser = new DataTable();
        //    UsersDAO objNewsDAO = new UsersDAO();
        //    v_dt_table = objNewsDAO.getAllUsersAcc(Session["Admin"].ToString());
        //    //v_dt_tableUser = objNewsDAO.getAllUsersRoleOne();
        //    v_dt_table.Merge(v_dt_tableUser, false, MissingSchemaAction.Ignore);
        //    return v_dt_table;
        //}
        private void reset_controls()
        {
            txtpassword.Text = "";
            txtusername.Text = "";
            drdRole.SelectedIndex = 0;
        }
        private bool LockUser(int ip_i_UserId)
        {
            UsersDAO v_userDAO = new UsersDAO();
            return v_userDAO.LockUser(ip_i_UserId);
        }
        private bool UnLockUser(int ip_i_UserId)
        {
            UsersDAO v_userDAO = new UsersDAO();
            return v_userDAO.UnlockUser(ip_i_UserId);
        }
        private bool check_exist_user(string ip_str_user)
        {
            return m_users_dao.check_exist_user(ip_str_user);
        }
        private int get_user_id_from_name(string ip_str_username)
        {
            return m_users_dao.get_id_from_user_name(ip_str_username);
        }
        #endregion

        #region Public Interfaces
        public string ConvertRole(int ip_i_role)
        {
            if (ip_i_role == 0) return "Admin";
            return "User";
        }
        public bool EnableDel(int ip_i_Role)
        {
            if (ip_i_Role == 0)
                return false;
            return true;
        }
        public string ConvertRoleToLock(int ip_i_role, int ip_i_UId)
        {
            int v_i_user_id_user_loged_in;
            v_i_user_id_user_loged_in = get_user_id_from_name(Session["Admin"].ToString());
            if (ip_i_role == 0)
            {
                if (ip_i_UId == v_i_user_id_user_loged_in)
                    return string.Format("<a href='/admin/ChangePassword.aspx?UId={0}'> <img title='Đổi mật khẩu' alt='Đổi mật khẩu' src='/admin/img/user_change.png' /></a>", ip_i_UId);
                return "";
            }
            else if (ip_i_role == 1) return string.Format("<a href='/admin/UserManagement.aspx?lock=true&UId={0}'> <img title='Khóa tài khoản' alt='Lock' src='/admin/img/lock.png' /></a>", ip_i_UId);
            return string.Format("<a href='/admin/UserManagement.aspx?lock=false&UId={0}'><img alt='Unlock' title='Mở khóa tài khoản' src='/admin/img/unlock.png' /></a>", ip_i_UId);
        }
        public string ConvertRoleToStatus(int ip_i_role)
        {
            if (ip_i_role != 2) return "Đang hoạt động";
            return "Đã bị khóa";
        }
        #endregion

        #region Events
        protected void btnclear_Click(object sender, EventArgs e)
        {
            try
            {
                reset_controls();
            }
            catch (Exception v_e)
            {
                lblMessage.Text = v_e.Message;
            }

        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                m_user.UserName = txtusername.Text.Trim();
                if (check_exist_user(m_user.UserName))
                {
                    string script;
                    script = "<script language='javascript'>alert('UserName đã tồn tại')</script>";
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "checkex", script);
                    return;
                }
                string v_str_pass = m_users_dao.Encrypt(txtpassword.Text, "bongda360", true);
                if (v_str_pass.Length > 20)
                    v_str_pass = v_str_pass.Substring(0, 20);
                m_user.Password = v_str_pass;
                m_user.UserLevel = Convert.ToInt32(drdRole.SelectedValue);
                if (m_users_dao.Insert(m_user))
                {
                    lblMessage.Text = "Thêm người dùng thành công";
                    lblMessage.Visible = true;
                    BindData();
                    reset_controls();
                }
                else lblMessage.Visible = false;
            }
            catch (Exception v_e)
            {
                lblMessage.Visible = true;
                lblMessage.Text = v_e.Message;
            }
        }
        protected void event_paging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grvGroupnews.PageIndex = e.NewPageIndex;
                this.BindData();
            }
            catch (Exception ip_e)
            {
                ip_e.ToString();
            }
        }
        #endregion

    }
}